import axios from "axios";
import {
  ElMessage
} from 'element-plus'
// import {
//   router
// } from '@/router'
import store from '@/store'

axios.defaults.timeout = 2000 * 1000;
//请求拦截器
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = "bearer " + token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


//响应拦截器
axios.interceptors.response.use(function (response) {
  const res = response.data
  if (res.code == 200) {
    return res
  } else {
    showError(res)
    return res
  }
}, error => {
  showError(error.response)
})


function showError(error) {
  if (error.status === 401) {
    localStorage.removeItem('token');
    store.state.login.token = ''
    location.reload(); //刷新就会返回登录界面
    //返回登录页面
    ElMessage({
      message: '登录状态已过期，请重新登录',
      type: 'error',
      duration: 2 * 1000
    })


  } else {
    ElMessage({
      message: error.msg || error.message || '服务异常',
      type: 'error',
      duration: 2 * 1000
    })
  }

}

export default axios